import { reactive, ref, watch } from "vue";
import { validateMobile, validateCode, validatePwd } from "@/utils/regular";
import { dataMiddleGroundBaseUserLoginBySms } from "@/api/data-middleground-base/base/user";
import { IForm, ICode, IUseForm } from "./types";
import { i18n } from "@/locale";
import { ElMessage } from "element-plus";
const useI18n: any = i18n.global;
const t = useI18n.t;

let formIcon = reactive<IForm>({
  mobile: "",
  password: "",
  code: "",
});
//提交按钮控制
const submitBtn = ref<boolean>(false);
//登录方式 1账号登录2短信登录
const loginType = ref<number>(1);
const ruleForm = ref<any>(null);
//表单验证规则
const rules = reactive({
  mobile: [
    {
      trigger: "change",
      validator: validateMobile,
    },
  ],
  password: [
    {
      trigger: "change",
      validator: validatePwd,
    },
  ],
  code: [
    {
      trigger: "change",
      validator: validateCode,
    },
  ],
});
//根据登录方式判断按钮状态
watch(loginType, () => {
  getSubmitStatus();
});
//表单验证事件
function validate(key: string, flag: boolean) {
  console.log(key);
  if (flag) {
    formIcon[key] = "ic-circle-correct-fill";
  } else {
    formIcon[key] = "ic-circle-wrong-fill";
  }
  getSubmitStatus();
}
//验证是否通过，登录按钮的状态
function getSubmitStatus() {
  if (loginType.value == 1) {
    if (
      formIcon.mobile == "ic-circle-correct-fill" &&
      formIcon.password == "ic-circle-correct-fill"
    ) {
      submitBtn.value = true;
    } else {
      submitBtn.value = false;
    }
  } else {
    if (
      formIcon.mobile == "ic-circle-correct-fill" &&
      formIcon.code == "ic-circle-correct-fill"
    ) {
      submitBtn.value = true;
    } else {
      submitBtn.value = false;
    }
  }
}

export default function validateForm(useLogin: any, useForm: IUseForm) {
  //验证码只限制输入数字
  const validateNum = function () {
    const reg = /\d/g;
    if (!reg.test(useForm.code)) {
      console.log(3333);
      useForm.code = "";
    }
  };
  //表单提交事件
  function submit() {
    ruleForm.value.validate((flag: boolean) => {
      if (flag) {
        if (loginType.value == 1) {
          useLogin.login();
          if (useForm.autoLogin) {
            useLogin.setUserInfos();
          } else {
            window.localStorage.removeItem("login");
          }
        } else {
          useLogin.codeLogin();
        }
      } else {
        ElMessage({
          message: t("validate.submit.error"),
          type: "warning",
        });
      }
    });
  }
  if (useForm.mobile && useForm.password) {
    formIcon.mobile = "ic-circle-correct-fill";
    formIcon.password = "ic-circle-correct-fill";
    submitBtn.value = true;
  } else {
  }
  return {
    validate,
    submit,
    rules,
    formIcon,
    submitBtn,
    ruleForm,
    loginType,
    validateNum,
  };
}
